<template>
  <div class="">
    <el-card>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="花名" prop="compere_name">
          <el-input
            v-model="ruleForm.compere_name"
            type="text"
            autocomplete="off"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="ruleForm.sex">
            <el-radio :value="0">男</el-radio>
            <el-radio :value="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="照片">
          <div class="el-upload" @click="openPhoto">
            <img
              v-if="ruleForm.photo"
              :src="URL + '/' + ruleForm.photo"
              style="width: 100px; height: 100px"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </div>
        </el-form-item>
        <el-form-item label="所带的本">
          <el-button type="primary" @click="openGgm">添加所带的本</el-button>
        </el-form-item>
        <el-form-item label="简介" prop="content">
          <el-input
            v-model="ruleForm.content"
            style="width: 540px"
            :rows="5"
            type="textarea"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="confirmDmAdd(ruleFormRef)">
            Confirm
          </el-button>
          <el-button @click="cancelDmAdd">Cancel</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 图片对话框 -->
    <el-dialog
      v-model="centerDialogVisible"
      title="添加"
      width="1000"
      align-center
      class="el-dialog"
    >
      <el-card style="max-width: 100%">
        <div class="btn">
          <el-upload
            class="avatar-uploader"
            :action="URL + '/admin/uploadpicture'"
            :show-file-list="false"
            name="picture"
            :data="{ type: 0 }"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            multiple
          >
            <el-button type="primary" size="large">单击上传</el-button>
          </el-upload>
        </div>
        <div class="bigbox">
          <div
            class="box"
            v-for="picture in pictures"
            :key="picture.id"
            @click="checkedPicture(picture)"
          >
            <img
              :src="URL + '/' + picture.img"
              style="width: 80px; height: 80px"
            />
            <!-- 选中 -->
            <div class="overspread" v-if="picture.id == checkedimgInfo.id">
              <el-icon><Check /></el-icon>
            </div>
          </div>
        </div>
        <el-pagination
          small
          background
          layout="prev, pager, next"
          :total="total"
          class="mt-4"
          :page-size="pageSize"
          @change="changePage"
          style="display: flex; justify-content: center"
        />
      </el-card>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirmPicture">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 剧本对话框 -->
    <el-dialog v-model="dialogTableVisible" title="Add" width="800">
      <div overflow="auto" style="height: 400px">
        <el-table :data="ggmList">
          <el-table-column label="是否选中" v-slot="{ row }">
            <el-checkbox v-model="row.isSelected" />
          </el-table-column>
          <el-table-column type="index" label="序号" width="150" />
          <el-table-column property="script_name" label="剧本名" />
          <el-table-column property="price" label="价格" />
          <el-table-column label="类型" v-slot="{ row }">
            <el-tag
              v-for="item in row.itemCateNameArr"
              :key="item"
              style="margin: 0 2px"
              >{{ item }}</el-tag
            >
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogTableVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirmGgm"> Confirm </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
const URL = import.meta.env.VITE_APP_API_URL;
import { useRoute, useRouter } from "vue-router";
const $router = useRouter();
const $route = useRoute();
import { reqDmList, ReqCompereUpdate } from "@/api/dm/index";
import { ReqDmList } from "@/api/dm/model";
import { reqGetPicture } from "@/api/picture/index";
import { reqGetPictureData } from "@/api/picture/model";
import { reqGgmList } from "@/api/ggm/index";
import { ResGgmList } from "@/api/ggm/model";
import { FormInstance, FormRules, UploadProps } from "element-plus";
const centerDialogVisible = ref<boolean>(false);
const dialogTableVisible = ref<boolean>(false);
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  id: 0,
  compere_name: "",
  sex: 0,
  photo: "",
  content: "",
  mmg_ids: "",
});
const page = ref<number>(1);
const pageSize = ref<number>(32);
const total = ref<number>(0);
const ggmPage = ref<number>(1);
const ggmPageSize = ref<number>(100);
const type = ref<number>(0);
const pictures = ref<reqGetPictureData[]>([]);
const checkedimgInfo = ref({ id: 0, img: "" });
const ggmList = ref<ResGgmList[]>([]);
const idArr = ref<number[]>([]);

const rules = ref<FormRules<typeof ruleForm>>({
  compere_name: [{ required: true, trigger: "blur", message: "请输入花名" }],
  sex: [{ required: true, trigger: "change", message: "请选择性别" }],
  content: [{ required: true, trigger: "blur", message: "请输入简介" }],
});

// 确定编辑
const confirmDmAdd = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      console.log(ruleForm.value);
      await ReqCompereUpdate(ruleForm.value);
      ElMessage({
        message: "编辑成功",
        type: "success",
      });
      $router.replace("/dmmanager/dmlist");
    } else {
      console.log("error submit!");
    }
  });
};
// 取消添加
const cancelDmAdd = () => {
  $router.replace("/dmmanager/dmlist");
};

const openGgm = () => {
  dialogTableVisible.value = true;
};

const confirmGgm = () => {
  idArr.value = [];
  ggmList.value.forEach((item) => {
    if (item.isSelected) {
      idArr.value.push(item.id);
    }
  });
  console.log(idArr.value);
  ruleForm.value.mmg_ids = idArr.value.join(",");
  dialogTableVisible.value = false;
};

// 添加图片
const openPhoto = () => {
  getPicture();
  checkedimgInfo.value = { id: 0, img: "" };
  centerDialogVisible.value = true;
};

// 选中图片
const checkedPicture = (picture: any) => {
  checkedimgInfo.value = picture;
};

// 确定图片
const confirmPicture = () => {
  ruleForm.value.photo = checkedimgInfo.value.img;
  centerDialogVisible.value = false;
};

// 分页
const changePage = (pageNum: number) => {
  page.value = pageNum;
  getPicture();
};

// 图片上传成功后
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  getPicture();
};

// 图片上传前
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

// 获取剧本列表
const getGgmList = async () => {
  let result = await reqGgmList({
    page: ggmPage.value,
    pageSize: ggmPageSize.value,
  });
  // ggmTotal.value = result.count;
  result.rows.forEach((item) => {
    if (item.cate_name) {
      item.itemCateNameArr = item.cate_name.split(",");
    }
    if (ruleForm.value.mmg_ids.includes(item.id.toString())) {
      item.isSelected = true;
    } else {
      item.isSelected = false;
    }
  });
  ggmList.value = result.rows;
};

const getPicture = async () => {
  let result = await reqGetPicture({
    type: type.value,
    page: page.value,
    pageSize: pageSize.value,
  });
  total.value = result.count;
  pictures.value = result.rows;
};

// 获取单个dm信息
const getDmInfo = async () => {
  let result = await reqDmList({
    page: 1,
    pageSize: 1,
    id: Number($route.query.id),
  });
  ruleForm.value = result.rows[0];
  console.log(ruleForm.value);
};

onMounted(async () => {
  await getDmInfo();
  getGgmList();
});
</script>

<style scoped lang="scss">
.el-upload {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  border: 1px dotted rgb(202 194 194);
}

.bigbox {
  display: flex;
  flex-wrap: wrap;

  .box {
    position: relative;
    margin: 10px 15px;

    .del {
      position: absolute;
      top: -8px;
      right: -8px;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 18px;
      height: 18px;
      cursor: pointer;
      background-color: black;
      border-radius: 50%;

      span {
        color: white;
      }
    }

    .overspread {
      position: absolute;
      inset: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 30px;
      color: #fff;
      // top: 0;
      // bottom: 0;
      // left: 0;
      // right: 0;
      background: rgb(0 0 0 / 40%);
    }
  }
}

.btn {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.el-dialog {
  height: 300px;
}
</style>
